/**
 * Created by WangWeiwei on 16-11-11.
 */
//拼接infowindow内容字串
var html = [];
/**构造信息输入框*/
(function () {
    html.push('<span style="font-size:12px">营业厅基本属性信息: </span><br/>');
    html.push('<table border="0" cellpadding="1" cellspacing="1" >');
    html.push('  <tr>');
    html.push('      <td align="left" class="common">名 称：</td>');
    html.push('      <td colspan="2"><input type="text" class="form-control" maxlength="50" size="18"  id="txtName"></td>');
    html.push('	     <td valign="top"><span class="star">*</span></td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('      <td  align="left" class="common">店长：</td>');
    html.push('      <td colspan="2">' +
        '               <div class="typeahead__container">'+
        '                   <div class="typeahead__field">'+
        '                       <span class="typeahead__query">' +
        '                       <input id="new-hall-staff" class="form-control" type="text" maxlength="50" size="18" >' +
        '                       </span>' +
        '                   </div>' +
        '               </div>');
    html.push('       </td>');
    html.push('	     <td valign="top"><span class="star">*</span></td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('      <td  align="left" class="common">类型：</td>');
    html.push('      <td  colspan="2">' +
        '                   <select  id="hallModel" class="form-control">' +
                                '<option value="1">私营</option>'+
                                '<option value="2">国营</option> '+
        '                   </select></td>');
    html.push('	     <td valign="top"><span class="star">*</span></td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('      <td  align="left" class="common">地址：</td>');
    html.push('      <td  colspan="2"><textarea  disabled   style="border:none;"  id="txtAddr"></textarea></td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('	     <td  align="center" colspan="3">');
    html.push('          <input type="button" name="btnOK"  onclick="fnOK()" value="确定">&nbsp;&nbsp;');
    html.push('		     <input type="button" name="btnClear" onclick="fnClear();" value="重填">');
    html.push('	     </td>');
    html.push('  </tr>');
    //TODO: 图片上传窗口
    html.push('</table>');
})();
var infoWin = new BMap.InfoWindow(html.join(""), {
    offset: new BMap.Size(0, -10),
    width : 200,
    height : 350});
//营业厅列表对象
var hallList = [];
//当前marker对象
var curMkr = null;
//职员序号
var staff = {};
//地址信息
var globleAttr = "";
var basePath;
//区域信息
var district;
//当前标记营业厅信息
var hallCur;
/**营业厅对象*/
function Hall(name,addr,tel) {
    this.name = name;
    this.addr = addr;
    this.tel = tel;
    this.staffId = 0;
    //营业厅类型
    this.hallModel = "";
    //区域信息
    this.district = "";
    //营业厅描述信息
    //TODO: 图片字符串
    this.desc = "";
    this.index = 0;
    //经纬度默认洛阳坐标
    this.x = 112.460752;
    this.y = 34.624123;
    //地图标记对象
    this.marker = null;
    //是否已经在页面上显示
    this.isShow = false;
    //是否允许显示
    this.canShow = false;
}


/**生成需要显示的营业厅列表HTML语句
 * 已经显示的不会再次生成
 * 返回营业厅列表字符串*/
function hallListHTML(hall) {
    var listHtml = [];
    listHtml.push('<section class="panel panel-info">');
    listHtml.push(  '<div class="panel-body">');
    listHtml.push('         <div class="clearfix m-b"> <div class="pull-left thumb m-r"> </div>');
    listHtml.push('     <div class="clear">');
    listHtml.push('             '+hall.name);
    listHtml.push('         <small class="block text-muted">');
    listHtml.push('             '+hall.addr);
    listHtml.push('         </small>')
    listHtml.push('         <i>'+hall.tel+'</i>');
    listHtml.push('     </div>');
    listHtml.push(' </div>');
    listHtml.push('</section>');
    return listHtml.join("");
}
//启用逆地址解析
function getAddr(addrPoint) {
    //地址解析类
    var geoc = new BMap.Geocoder();
    geoc.getLocation(addrPoint,function (rs) {
        //设置地址为点击点的地址
        document.getElementById("txtAddr").value =  rs.address;
        globleAttr = rs.address;
        //设置区域信息
        var addComp = rs.addressComponents;
        district = addComp.district;
});
}

/**为店长名字输入框添加搜索引擎
 * @param searchURL 要处理搜索信息的地址*/
function staffNameTypeAhead(searchURL) {
    $(function () {
        $.typeahead({
            input: "#new-hall-staff",
            minLength: 1,
            dynamic: true,
            delay: 500,
            backdrop: {
                "background-color": "#fff"
            },
            //显示模板
            template: function (query, item) {
                var color = "#777";
                return '<span>'  +
                    '<span>{{staffName}} <small style="color: ' + color + ';">编号:{{staffId}}</small></span>' +
                    '<small>手机号:{{phone}}</small>' +
                    "</span>"
            },
            emptyTemplate: "没有关于 {{query}} 的结果",
            source: {
                //数据源
                user: {
                    //要显示的属性
                    display: "staffName",
                    data: [],
                    ajax:
                    {
                        type: "GET",
                        url: searchURL,
                        //path: "data.user",
                        data: {
                            param: "{{query}}"
                        }
                    }
                }
            },
            callback: {
                onClick: function (node, a, item, event) {
                    //item为已选择的对象
                    staff = item;
                }
            },
            debug: true
        });
    })
}
/*function staffNameTypeAhead(searchURL) {
        var states = new Bloodhound({
        datumTokenizer: function () {
            return Bloodhound.tokenizers.obj.whitespace("word")
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        // 在文本框输入字符时才发起请求
        remote: {
            url: searchURL + "?param=%QUERY",
            wildcard: '%QUERY'
        },
        limit: 10
    });

    states.initialize();

    $("#new-hall-staff").typeahead(null,{
            name: 'states',
            displayKey: 'word',
            source: states.ttAdapter()
        }).on('typeahead:selected', function (e, datum) {
        var selectItemVal =
            $('#new-hall-staff').val().
                substr(0, $("#selectedRecipients").val().length - 2);
        $("#selectedItems").append("<span class='label label-primary' style='cursor:pointer' onclick='removeSelected(this," + datum["rkey"] + ")'><span class='glyphicon glyphicon-minus' aria-hidden='true'></span> " + datum["word"] + "</span> ");
        $('#add-goods-productor').blur();
    });

    //移除已选择项
    function removeSelected(opt, removeId) {
        $(opt).remove();
        var selectRkey = $("#selectedRecipients").val();
        var arr = selectRkey.split("@@");
        var arr2 = $(arr).map(function (ind, val) {
            if (parseInt(val) == parseInt(removeId)) {
                //arr.remove
            } else {
                return val;
            }
        }).get().join("@@");
        $("#selectedRecipients").val(arr2);
    }
}
*/
/**将所有营业厅信息在页面上去展示*/
function showHallList() {
    $("#hallList").html("");
    for (var index in hallList){
        $("#hallList").append(hallListHTML(hallList[index]));
    }
}
/**将营业厅信息在前台保存,并把按钮恢复到初始状态
 * @param hall 提交成功的营业厅对象*/
function newHallSuccess(hall) {
    hall.marker = curMkr;
    hallList.push(hall);
    $("#cancle-new-hall-btn").hide();
    $("#new-hall-btn").show();
    showHallList();
}

/**获取当前营业厅类型*/
function getHallModel() {
    var hallModel = document.getElementById("hallModel").value;
    if (hallModel == 1){
        return '私营';
    }
    if (hallModel == 2){
        return '国营';
    }
}
/**
 * 提交新标记营业厅信息*/
function fnOK(){
    var name = encodeHTML(document.getElementById("txtName").value);
    var staffName = encodeHTML(document.getElementById("new-hall-staff").value);
    var addr = document.getElementById("txtAddr").value;
    var desc = "";
    var hallModel = getHallModel();
    if(!name  || !addr){
        alert("星号字段必须填写");
        return;
    }

    //在此用户可将数据提交到后台
    if (staff.staffName == staffName){
        var hall = new Hall(name,addr,staff.phone);
        hall.x = curMkr.getPosition().lng;
        hall.y = curMkr.getPosition().lat;
        hall.staffId = staff.staffId;
        hall.district = district;
        hall.hallModel = hallModel;
        hall.desc = desc;
        hallCur = hall;
        $.ajax({
                url : basePath + "/BusinessHall/admin/newHall/map",
                data : hall,
                async : false,
                type : "POST",
                success : function (data){
                    var result = JSON.parse(data);
                    if (result.status == 1){
                        //新建营业厅成功
                        newHallSuccess(hall);
                        newHallOk();
                        alert("新建营业厅成功");
                    }else {
                        //新增营业厅失败
                    }
                }
            }
        );
    }else {
        alert("店长不存在或没有可用的手机号")
    }

    //关闭弹出框,为标记添加注释
    function newHallOk() {
        if (curMkr) {
            //设置label
            var lbl = new BMap.Label(name, {offset: new BMap.Size(20, 0)});
            lbl.setStyle({border: "solid 1px gray"});
            curMkr.setLabel(lbl);

            //设置title
            var title = "名称: " + name + "\n\r" + "地址: " + addr + "\n\r" + "电话: " + desc;
            curMkr.setTitle(title);
        }
        if (infoWin.isOpen()) {
            map.closeInfoWindow();
        }
    }
}

//输入校验
function encodeHTML(a){
    return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

//重填数据
function fnClear(){
    document.getElementById("txtName").value = "";
    document.getElementById("txtAddr").value = globleAttr;

  //  document.getElementById("hallModel").value = "";
    document.getElementById("new-hall-staff").value = "";
}

/**新建营业厅按钮*/
function newHallBtn() {
    // 定义一个控件类，即function
    function AddHallControl(){
        // 设置默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
        this.defaultOffset = new BMap.Size(20, 10);
    }
// 通过JavaScript的prototype属性继承于BMap.Control
    AddHallControl.prototype = new BMap.Control();
    // 自定义控件必须实现initialize方法，并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    AddHallControl.prototype.initialize = function(map){
// 创建一个DOM元素
        var div = $("#new-hall-btn")[0];
        // 添加DOM元素到地图中
        map.getContainer().appendChild(div);
        // 将DOM元素返回
        return div;
    };

    function CancelAddHallControl(){
        // 设置默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
        this.defaultOffset = new BMap.Size(10, 20);
    }
// 通过JavaScript的prototype属性继承于BMap.Control
    CancelAddHallControl.prototype = new BMap.Control();
    // 自定义控件必须实现initialize方法，并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    CancelAddHallControl.prototype.initialize = function(map){
// 创建一个DOM元素
        var div = $("#cancle-new-hall-btn")[0];
        // 添加DOM元素到地图中
        map.getContainer().appendChild(div);
        // 将DOM元素返回
        return div;
    }

    var addHallBtn = new AddHallControl();
    map.addControl(addHallBtn);
    var cancelAddHallBtn = new CancelAddHallControl();
    map.addControl(cancelAddHallBtn);
}